package;
import hxvid.Server;
import hxvid.Data;
import hxvid.Logger;
//import neko.vm.Loader;
//import neko.vm.Module;
class Main
{	
	static function main() 
	{
		var config = processCommandLine();
		var server = new Server(config);
		try 
		{
			//trace("Starting hxis2 on "+config.host+":"+config.port);
			server.run(config.host, config.port);
		} 
		catch( e : Dynamic )
		{
			if( e == "std@socket_bind" )	e = "Error : std@socket_bind (port " + config.port + " in use?)";
			neko.Lib.rethrow(e);
		}
	}
	static function processCommandLine():ServerConfig
	{
		return switch(neko.Sys.args().length)
		{
			case 0 : 
				processServerConfig();
			case 1 : 
				processServerConfig(neko.Sys.args()[0]);
			case 2 : 
				var conf = processServerConfig();
				conf.host = neko.Sys.args()[0];
				conf.port = Std.parseInt(neko.Sys.args()[1]);
				conf;
			default :
				processServerConfig();
		};
	}
	static function processServerConfig(?configFile:String="config.xml"):ServerConfig
	{
		var config = Server.defaultConfig;
		try
		{
			var source = neko.io.File.getContent(configFile);
			var xml = Xml.parse(source).firstElement();
			for(field in Reflect.fields(config))
				if(xml.exists(field))
					Reflect.setField(config, field, switch(field)
					{
						case "host", "appsDir", "logFile": 
							cast xml.get(field);
						case "flvBufferTime", "connectLag":
							cast Std.parseFloat(xml.get(field));
						case "port", "listenValue", "messageHeaderSize", "threadsCount":
							cast Std.parseInt(xml.get(field));
						case "clientBufferSize","minReadBufferSize","maxReadBufferSize", "writeBufferSize","blockingBytes":
							cast Std.parseInt(xml.get(field))*1024;
						default:
							trace("attribute:"+field +" not found in " + configFile +". Using default value:" + Reflect.field(config,field));
							cast Reflect.field(config,field);
					});
		}
		catch(e:Dynamic)
		{
			trace(e);
		}
		return config;
	}
}